package com.city.ajax.house;
import com.city.domain.house.*;
import com.city.domain.pub.PubHouseinfo;
import com.city.domain.pub.PubUser;
import com.city.service.house.RealHouseSearch;
import com.city.service.pub.PubHouseinfoService;
import com.city.service.pub.PubUserService;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

import com.city.domain.city.CityTown;
import com.city.domain.city.CityVillage;
import com.city.service.city.CityTownService;
import com.city.service.city.CityVillageService;
import com.city.service.house.rentHouseService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.management.Query;

@CrossOrigin(origins = "*",maxAge = 3600)
@RestController

public class HouseAjax {
    /**
     * @deprecation: 获取出租房屋信息，并处理传给出租统计界面
     * @author: 方少
     * @param 无
     * @date: 2018/7/28 19：02
     */
    @Autowired
    private rentHouseService rentHouses;
    @Autowired
    private CityTownService cityhouse;
    @GetMapping(value = "/getRentHouse/town")
    public List<townwithdata> housesList(){
        List<cityHouseinfo> list = rentHouses.findAll();
        Map<Integer,Integer> isrent = new HashMap<>();
        Map<Integer,Integer> norent = new HashMap<>();
        Map<Integer,Integer> avg = new HashMap<>();
        for(cityHouseinfo chi : list){
            double sum = 0.0;
            Integer id = chi.getTown();
            //如果表中存在
            if(isrent.containsKey(id)){
                //判断是否为出租状态
                if(chi.getStatus().equals("出租")){
                    Integer temp =  (Integer) isrent.get(id) + 1;
                    isrent.put(id,temp);
                    temp = (Integer)avg.get(id) + chi.getPrice();
                    avg.put(id,temp);
                }
                if(chi.getStatus().equals("求租")){
                    Integer temp =  (Integer) norent.get(id) + 1;
                    norent.put(id,temp);
                }
            }else{
                if(chi.getStatus().equals("出租")){
                    isrent.put(id,1);
                    norent.put(id,0);
                    avg.put(id,chi.getPrice());
                }
                if(chi.getStatus().equals("求租")){
                    isrent.put(id,0);
                    norent.put(id,1);
                    avg.put(id,0);
                }
            }
        }
        List <townwithdata> resd = new ArrayList<>();
        List<CityTown> ct = cityhouse.findName("2615");

        for(Integer key:isrent.keySet()){
            String name = "";
            Integer is = 0;
            Integer no = 0;
            double pri = 0.0;
            for(CityTown ct2 : ct){
                if(ct2.getTownId() == key){
                    name = ct2.getTownName();
                    is = (Integer)isrent.get(key);
                    no = (Integer)norent.get(key);
                    int s = avg.get(key);
                    if(is != 0)
                        pri = (double) s / is;
                    break;
                }
            }

            resd.add(new townwithdata(key.toString(),name,is,no,pri));
        }
        return resd;
    }

    /**
     * @deprecation: 获取出租房屋详细信息信息。
     * @author: 方少
     * @param villageCode
     * @date: 2018/7/28 19：02
     */
    @Autowired
    private CityVillageService cityv;
    @Autowired
    private CityTownService ctt;
    @GetMapping(value = "/getRentHouse/townDetail")
    public List<townwithdata> villageList(@RequestParam("TownCode") Integer code) {
        List<CityVillage> cv = cityv.findName(code);
        List<townwithdata> result = new ArrayList<>();
        Map<Integer, Integer> isrent = new HashMap<>();
        Map<Integer, Integer> norent = new HashMap<>();
        Map<Integer, Integer> avg = new HashMap<>();
        List<cityHouseinfo> all = rentHouses.findByTown(code);
        for (cityHouseinfo chi : all) {
            if (isrent.containsKey(chi.getVillage())) {
                if (chi.getStatus().equals("出租")) {
                    Integer temp = isrent.get(chi.getVillage()) + 1;
                    isrent.put(chi.getVillage(), temp);
                    temp = avg.get(chi.getVillage()) + chi.getPrice();
                    avg.put(chi.getVillage(), temp);
                }
                if (chi.getStatus().equals("求租")) {
                    Integer temp = norent.get(chi.getVillage()) + 1;
                    norent.put(chi.getVillage(), temp);
                    temp = avg.get(chi.getVillage()) + chi.getPrice();
                    avg.put(chi.getVillage(), temp);
                }
            } else {
                if (chi.getStatus().equals("出租")) {
                    isrent.put(chi.getVillage(), 1);
                    norent.put(chi.getVillage(), 0);
                } else if (chi.getStatus().equals("求租")) {
                    norent.put(chi.getVillage(), 1);
                    isrent.put(chi.getVillage(), 0);
                }
                avg.put(chi.getVillage(), chi.getPrice());
            }
        }
        for (CityVillage cityvillage : cv) {
            if (isrent.containsKey(cityvillage.getVillageId())) {
                Integer id = cityvillage.getVillageId();
                Integer t = avg.get(id);
                double av = 0.0;
                if (isrent.get(id) != 0 || norent.get(id) != 0) {
                    av = (double) t / (isrent.get(id) + norent.get(id));
                    BigDecimal bg = new BigDecimal(av);
                    av = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
                result.add(new townwithdata(id.toString(), cityvillage.getVillageName(), isrent.get(id), norent.get(id), av));
            }
        }
        return result;
    }

    /**
     * @deprecation:实有房屋统计获取信息
     * @author: 方少
     * @param none
     * @date: 2018/7/29 11:04
     */
    @Autowired
    private RealHouseSearch rhs;
    @GetMapping(value = "/getHouseinfo")
    public List<SummaryHouse> realHouseList(){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        //今年的数据
        List<PubHouseinfo> listThisMonth = rhs.findByUpdateTimeLike("%" + year  +"%");
        //上一年的数据
        List<PubHouseinfo> listLastMonth = rhs.findByUpdateTimeLike("%" + (year - 1)  +"%");
        Map<String,Integer> Nowsum = new HashMap<>();
        Map<String,Integer> Lastsum = new HashMap<>();
        List<CityTown> townList =  ctt.findName("2615");
        //初始化列表：要展示所有乡镇级别的情况。
        for(CityTown te : townList){
            Nowsum.put(te.getTownName(),0);
            Lastsum.put(te.getTownName(),0);
        }
        for(PubHouseinfo p : listThisMonth){
            Integer temp = Nowsum.get(p.getTown()) + 1;
            Nowsum.put(p.getTown(),temp);
        }

        for(PubHouseinfo p : listLastMonth){
            Integer temp = Lastsum.get(p.getTown()) + 1;
            Lastsum.put(p.getTown(),temp);
        }
        List<SummaryHouse> sh = new ArrayList<>();
        for(CityTown te : townList){
            sh.add(new SummaryHouse(
                    te.getTownId(),
                    te.getTownName(),
                    Nowsum.get(te.getTownName()),
                    Lastsum.get(te.getTownName())
            ));
        }
        return sh;
    }


    /**
     * @deprecation:实有房屋统计获取,查询关键字信息
     * @author: 方少
     * @param keyString
     * @date: 2018/7/30 10:00
     */
    @GetMapping(value = "/getHouseinfoByKey")
    public List<SummaryHouse> realHouseListByKey(@RequestParam("KeyString") String keyString){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        //这个月数据
        List<PubHouseinfo> listThisMonth = rhs.findByUpdateTimeLike("%" + year +"%");
        //上个月数据
        List<PubHouseinfo> listLastMonth = rhs.findByUpdateTimeLike("%" + (year - 1 ) +"%");
        Map<String,Integer> Nowsum = new HashMap<>();
        Map<String,Integer> Lastsum = new HashMap<>();
        List<CityTown> townList =  ctt.findName("2615");
        List<SummaryHouse> sh = new ArrayList<>();
        for(PubHouseinfo p : listThisMonth){
            if(p.getTown().indexOf(keyString) >= 0){
                if(Nowsum.containsKey(p.getTown())){
                    Integer temp = Nowsum.get(p.getTown()) + 1;
                    Nowsum.put(p.getTown(),temp);
                }else{
                    Nowsum.put(p.getTown(),1);
                    Lastsum.put(p.getTown(),0);
                }
            }
        }

        for(PubHouseinfo p : listLastMonth){
            if(p.getTown().indexOf(keyString) >= 0){
                if(Lastsum.containsKey(p.getTown())){
                    Integer temp = Lastsum.get(p.getTown()) + 1;
                    Lastsum.put(p.getTown(),temp);
                }else{
                    Nowsum.put(p.getTown(),0);
                    Lastsum.put(p.getTown(),1);
                }
            }
        }

        for(CityTown ct : townList){
            if(Nowsum.containsKey(ct.getTownName()) || Lastsum.containsKey(ct.getTownName())){
                sh.add(new SummaryHouse(ct.getTownId(),ct.getTownName(),Nowsum.get(ct.getTownName()),Lastsum.get(ct.getTownName())));
            }
        }
        return sh;
    }

    /**
    *@author 方少
    *@Description 实有房屋统计详细数据处理与反馈
    *@Date 2018/8/4 9:23
    *@Param
    *@return
    */
    @GetMapping(value = "/getRealHouseinfoByKey")
    public List<realHouseCountInfo> realHouseinforByKey(@RequestParam("KeyString") String keyString){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        List<realHouseCountInfo> result = new ArrayList<>();
        List<CityTown> cityTownsinfo = ctt.findName("2615");
        Integer townId = 0;
        //由于数据库存的是镇的名字，接口部分师兄做的还不敢改，只能先通过镇名获取id。
        for(CityTown ct : cityTownsinfo){
            if(ct.getTownName().equals(keyString)){
                townId = ct.getTownId();
                break;
            }
        }
        List<CityVillage> cvList = cityv.findName(townId);
        Double TownAllArea = 0.0;
        for(CityVillage cv : cvList){
            Integer areasum = 0;
            List<PubHouseinfo> cvareas =  rhs.findByVillage(cv.getVillageName());
            for(PubHouseinfo pi : cvareas){
                areasum += pi.getArea();
            }
            TownAllArea += areasum;
        }

        for(CityVillage cv : cvList){
            Long num = rhs.countByVillageAndUpdateTimeLike(cv.getVillageName(),"%"+year+"%");
            //Long num2 = rhs.countByVillageAndUpdateTimeLike(cv.getVillageName(),"%"+(year - 1)+"%");
            Long sum = rhs.countByVillage(cv.getVillageName());
            List<PubHouseinfo> cvareas =  rhs.findByVillage(cv.getVillageName());
            Integer areasum = 0;
            for(PubHouseinfo pi : cvareas){
                areasum += pi.getArea();
            }
            double pre = areasum/TownAllArea;
            String precent = new BigDecimal((pre * 100)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue() + "%";
            //计算增长率
            double increasePre = num;
            if((sum - num) == 0)
                increasePre = 0.0;
            else
                increasePre = increasePre / (sum - num);

            result.add(new realHouseCountInfo(cv.getVillageId(),cv.getVillageName(),sum,areasum,num,precent,increasePre));
        }
        return result;
    }

    /**
    *@author 方少
    *@Description
    *@Date 2018/8/6 9:08
    *@Param
    *@return
    */
    @Autowired
    private PubUserService pus;
    @GetMapping(value = "/ConfirmUser")
    public Integer confirmUser(@RequestParam("UserName") String name,@RequestParam("TellPhone") String tellPhone){
        Integer result = -1;
        PubUser pu =  pus.getUserByTellAndName(name,tellPhone);
        if(pu == null)
            result = -1;
        else
            result = pu.getId();
        return result;
    }
}
